package com.xln.furn.interceptor;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xln.furn.service.UserService;
import com.xln.furn.userVO.User;
import com.xln.furn.util.Result;
import com.xln.furn.util.Token;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

import static com.xln.furn.controller.LoginController.threadLocal;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Resource
    private UserService userService;
    @Resource
    private ObjectMapper objectMapper;

    // 创建一个ThreadLocal变量
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // String requestURI = request.getRequestURI();
        // StringBuffer requestURL = request.getRequestURL();
        // log.info("{},{}",requestURI,requestURL);
        // Object user = request.getSession().getAttribute("user");
        // if (user == null){
        //
        //     response.sendRedirect("/login2`");
        //     return false;
        // }


//        非前后端的登入
//        try {
//            String token = request.getHeader("token");
//            Map<String,Object> map = Jwts.parser()
//                    .setSigningKey("eHVsaW5pYW4K")
//                    .parseClaimsJws(token)
//                    .getBody();
//            Integer userId =(Integer) map.get("userId");
//            User user = userService.getById(userId);
//            if (user == null){
//                response.sendRedirect("login2");
//                return false;
//            }
//
//        } catch (Exception e) {
//            e.printStackTrace();
//            response.sendRedirect("login2");
//            return false;
//        }
//
//
//        return true;
//    }
//前后端分离登入

        response.setContentType("application/json;charset=utf-8");
        try {
            String token = request.getHeader("token");
            log.info("token:{}",token);
            Map map = Token.parseToken(token);
            String userName =(String) map.get("userId");
            User user = userService.getOne(Wrappers.<User>lambdaQuery().eq(User::getName,userName));
            if (user == null){

                Result result = Result.fail(401, "用户不存在！");
                response.getWriter().write(objectMapper.writeValueAsString(result));
                return false;
            }
            String password =( String) map.get("password");
            log.info("password:{}",password);
            if (!user.getPassword().equals(password)){

                Result result = Result.fail(402, "用户未登入！");
                response.getWriter().write(objectMapper.writeValueAsString(result));
                return false;
            }
            threadLocal.set(user);



        } catch (Exception e) {
            e.printStackTrace();
//            response.sendRedirect("login2");
            log.error("token验证异常", e);
            Result<Object> result = Result.fail(500, "服务器内部错误");
            response.getWriter().write(objectMapper.writeValueAsString(result));
            return false;
        }


        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        threadLocal.remove();
    }
}
